from bsccommonlib.csv_persister import CsvPersister
from bsccommonlib.pycommons import abstract
from targetmonitoring.target_models import TargetSubmit
from targetmonitoring.menu_item import MenuItem

    
class AbstractSubmitToTargetClient(object):
    def __init__(self, csv_file,target_object):
        self.exit = False
        self.csv_file = csv_file
        self.persister = CsvPersister(csv_file)
        self.target_object = target_object
        self.menu_item_list = [
                         MenuItem(self._exit, 'Exit menu', index = 0)
                        ,MenuItem(self._submit_actual, 'Submit Actual')
                        ,MenuItem(self._submit_diff, 'Submit Diff')
                        
                    ]

    @abstract 
    def _on_display_requested(self, selection_list):
        pass

    @abstract
    def _on_target_list_display_request(self, target_list):
        pass
    
    @abstract
    def _on_target_submit_request(self, target_submit_class, diff=0):
        pass
   
    @abstract
    def _on_exit(self):
        pass 
    
    def _fire_on_submit_completed(self, target_submit, diff=0):
        for submit in self.persister.get_list(TargetSubmit):
                if submit.issue_date.toordinal() == target_submit.issue_date.toordinal():
                    self.persister.remove(submit)
                    break
        
        if diff != 0:
            total_points = 0
            for submit in self.persister.get_list(TargetSubmit):
                total_points += submit.point
                
            if self.target_object.increase == 0:
                target_submit.point = self.target_object.initial_status - total_points - target_submit.point
            else:
                target_submit.point = target_submit.point - (self.target_object.initial_status + total_points)
             
        self.persister.add(target_submit)
        
    def _exit(self):
        self.exit = True
        self._on_exit()

    def _submit_diff(self):
        self._on_target_submit_request(TargetSubmit)
    
    def _submit_actual(self):
        self._on_target_submit_request(TargetSubmit,1)
        
    def _fire_item_selected(self, selection, **kargs):
        for menu_item in self.menu_item_list:
            if menu_item.index == selection:
                menu_item.bind_method(**kargs)
                break   

        
    def start(self):
        while (self.exit is False):
            self._on_display_requested(self.menu_item_list)





